package com.example.batch.config;

import com.example.batch.constant.JobConstant;
import com.example.batch.process.IdEnhanceProcess;
import com.example.batch.process.IdFilterProcess;
import com.example.batch.reader.MyFlatFileReader;
import com.example.batch.writer.MyFlatFileItemWriter;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.batch.item.support.CompositeItemProcessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.List;

/**
 * @author LiYuhang
 * @version 0.1
 * @application
 * @Date 2021/7/17 20:34
 * @Description TODO
 */
@Configuration
public class MultiProcessConfig extends BaseConfig {

    final MyFlatFileReader reader;
    final MyFlatFileItemWriter writer;
    final IdEnhanceProcess idEnhanceProcess;
    final IdFilterProcess idFilterProcess;

    @Autowired
    public MultiProcessConfig(IdFilterProcess idFilterProcess,MyFlatFileReader reader,MyFlatFileItemWriter writer,IdEnhanceProcess idEnhanceProcess) {
        this.idFilterProcess = idFilterProcess;
        this.reader = reader;
        this.writer = writer;
        this.idEnhanceProcess = idEnhanceProcess;
    }


    @Bean
    public Step multiProcessStep() {
        return stepBuilderFactory.get("multiProcessStep")
                .<List<String>, List<String>>chunk(100)
                .reader(reader)
                .processor(multiProcess())
                .writer(writer)
                .build();
    }


    @Bean
    public Job multiProcessJob() {
        return jobBuilderFactory.get(JobConstant.MULTI_PROCESS_JOB_DEMO)
                .incrementer(new RunIdIncrementer())
                .listener(myJobListener)
                .start(multiProcessStep())
                .build();
    }

    @Bean
    public CompositeItemProcessor multiProcess(){
        CompositeItemProcessor compositeItemProcessor=new CompositeItemProcessor();
        List<ItemProcessor> delegates=new ArrayList<>();
        delegates.add(idFilterProcess);
        delegates.add(idEnhanceProcess);
        compositeItemProcessor.setDelegates(delegates);
        return compositeItemProcessor;
    }


}
